import axios from 'axios'

const instance = axios.create()

export function http(apiUrl, configObj) {
  //传入的接口配置参数
  let {
    method = 'GET',
    params = {},
    data = {},
    timeout = 180000, //时间限制请求30分钟
    contentType = 'application/json',
    onUploadProgress = false
  } = configObj

  return instance({
    url: apiUrl, method: method, params: params, data: data, timeout: timeout,
    headers: {
      'Content-Type': contentType,
      token: localStorage.getItem('token') || ''
    },
    ...(onUploadProgress ? { onUploadProgress: onUploadProgress } : {})
  })
}

instance.interceptors.response.use(response => {
  if (response && response.data) return Promise.resolve(response.data)
  else return Promise.reject(Error('服务器异常,无响应'))
}, error => {
  if (axios.isCancel(error) || error.code == 'ECONNABORTED')
    return Promise.resolve({ state: true, msg: null, obj: [], code: 200 })

  return Promise.reject(Error('网络异常,请重试'))
})

instance.interceptors.request.use(config => {
  return config
}, error => {
  if (axios.isCancel(error))
    return Promise.resolve({ state: true, msg: null, obj: [], code: 200 })

  return Promise.reject(Error('网络异常,请重试'))
})
